const WebSocket = require('ws');

class DataHandler {
    constructor() {
        this.dataWss = new WebSocket.Server({ noServer: true });
        this.subscribers = new Map(); // 存储订阅者
        this.setupDataHandler();
        this.startDataPublishing();
    }

    setupDataHandler() {
        this.dataWss.on('connection', (ws, request) => {
            console.log('数据客户端已连接数据服务器');
            ws.wsType = 'data';
            ws.subscriptions = new Set(); // 该客户端订阅的主题

            ws.on('message', (message) => {
                try {
                    const data = JSON.parse(message);
                    console.log("解析后的message", data);
                    this.handleDataMessage(ws, data);
                } catch (error) {
                    ws.send(JSON.stringify({ type: 'error', message: '消息格式错误' }));
                }
            });

            ws.on('close', (code, reason) => {
                console.log(`数据客户端断开连接: ${code} - ${reason}`);
                this.handleClientDisconnect(ws);
            });

            ws.send(JSON.stringify({ type: 'welcome', message: '数据连接已建立' }));
        });
    }

    handleDataMessage(ws, data) {
        switch (data.type) {
            case 'getData':
                this.sendData(ws, data.dataType || 'default');
                break;
            case 'sendData':
                console.log('收到客户端数据消息', data);
                this.processClientData(ws, data);
                break;
            case 'subscribe':
                this.subscribeToTopic(ws, data.topic);
                break;
            case 'unsubscribe':
                this.unsubscribeFromTopic(ws, data.topic);
                break;
            case 'getSubscriptions':
                this.sendSubscriptions(ws);
                break;
            default:
                ws.send(JSON.stringify({ type: 'error', message: '未知的数据消息类型' }));
        }
    }

    subscribeToTopic(ws, topic) {
        if (!topic) {
            ws.send(JSON.stringify({ type: 'error', message: '主题不能为空' }));
            return;
        }

        ws.subscriptions.add(topic);
        
        // 添加到订阅者列表
        if (!this.subscribers.has(topic)) {
            this.subscribers.set(topic, new Set());
        }
        this.subscribers.get(topic).add(ws);

        ws.send(JSON.stringify({ 
            type: 'subscribed', 
            topic: topic,
            message: `已订阅主题: ${topic}`
        }));
    }

    unsubscribeFromTopic(ws, topic) {
        ws.subscriptions.delete(topic);
        
        // 从订阅者列表中移除
        if (this.subscribers.has(topic)) {
            this.subscribers.get(topic).delete(ws);
        }

        ws.send(JSON.stringify({ 
            type: 'unsubscribed', 
            topic: topic,
            message: `已取消订阅主题: ${topic}`
        }));
    }

    sendSubscriptions(ws) {
        ws.send(JSON.stringify({
            type: 'subscriptions',
            topics: Array.from(ws.subscriptions)
        }));
    }

    sendData(ws, dataType) {
        const data = this.generateData(dataType);
        ws.send(JSON.stringify({
            type: 'data',
            dataType: dataType,
            content: data,
            timestamp: new Date().toISOString()
        }));
    }

    generateData(dataType) {
        switch (dataType) {
            case 'tableData':
                return {
                    rows: [
                        { id: 1, name: '张三', age: 25, status: 'active' },
                        { id: 2, name: '李四', age: 30, status: 'inactive' },
                        { id: 3, name: '王五', age: 28, status: 'active' }
                    ],
                    total: 3
                };
            case 'chartData':
                return {
                    labels: ['一月', '二月', '三月', '四月'],
                    values: [10, 20, 15, 25]
                };
            default:
                return {
                    message: '这是默认数据',
                    value: Math.random() * 100
                };
        }
    }

    processClientData(ws, data) {
        console.log('处理客户端数据:', data);
        // 这里可以添加数据处理逻辑
        ws.send(JSON.stringify({
            type: 'dataProcessed',
            message: '数据已处理',
            originalData: data
        }));
    }

    handleClientDisconnect(ws) {
        // 清理订阅
        ws.subscriptions.forEach(topic => {
            if (this.subscribers.has(topic)) {
                this.subscribers.get(topic).delete(ws);
            }
        });
    }

    startDataPublishing() {
        // 定时推送数据到订阅者
        setInterval(() => {
            this.publishData('tableData', {
                type: 'update',
                timestamp: new Date().toISOString(),
                data: {
                    value: Math.random() * 100,
                    status: 'ok'
                }
            });
        }, 5000);

        // 定时推送图表数据
        setInterval(() => {
            this.publishData('chartData', {
                type: 'chartUpdate',
                timestamp: new Date().toISOString(),
                data: {
                    labels: ['一月', '二月', '三月', '四月'],
                    values: [
                        Math.random() * 50,
                        Math.random() * 50,
                        Math.random() * 50,
                        Math.random() * 50
                    ]
                }
            });
        }, 8000);
    }

    publishData(topic, data) {
        if (this.subscribers.has(topic)) {
            this.subscribers.get(topic).forEach(ws => {
                if (ws.readyState === WebSocket.OPEN) {
                    ws.send(JSON.stringify(data));
                }
            });
        }
    }

    getServer() {
        return this.dataWss;
    }
}

module.exports = DataHandler;